using Digitalmes.Domain.Entities.Mes.Processes;

namespace Digitalmes.Application.Mes.Processes.StepTasks.Commands;

/// <summary>
/// 工步创建命令。
/// </summary>
public sealed record CreateStepTaskCommand(ProcStepTaskDto StepTask) : IRequest<IResult<bool>>;

internal sealed class CreateStepTaskCommandHandler(IRepository<ProcStepTask> repo) : IRequestHandler<CreateStepTaskCommand, IResult<bool>>
{
    const int GroupSpan = 1000; // 分组区间

    public async Task<IResult<bool>> Handle(CreateStepTaskCommand request, CancellationToken cancellationToken)
    {
        // 检查工步代码是否重复
        var stepTask = request.StepTask.Adapt<ProcStepTask>();
        if (await repo.IsAnyAsync(m => m.StepId == stepTask.StepId && m.TaskCode == stepTask.TaskCode, cancellationToken))
        {
            return Result.Failure("工步代码已存在");
        }

        if (stepTask.Seq % GroupSpan != 0)
        {
            // 非整数倍，按给定的值来设置
            // 检查 seq 是否重复
            if (await repo.IsAnyAsync(m => m.StepId == stepTask.StepId && m.Seq == stepTask.Seq, cancellationToken))
            {
                return Result.Failure("工步顺序号已存在");
            }
        }
        else
        {
            // seq 为分组区间的整数倍，在区间内自增
            var stepSpan = stepTask.Seq + GroupSpan;
            var max = await repo.MaxAsync(m => m.StepId == stepTask.StepId && m.Seq < stepSpan, m => m.Seq, cancellationToken);
            if (max < stepTask.Seq)
            {
                // 查询的最大值未达到指定区间内最小值时，按区间最小值计算
                stepTask.Seq++; // 区间最小值+1
            }
            else
            {
                stepTask.Seq = max + 1;
            }
        }

        var ok = await repo.InsertAsync(stepTask, cancellationToken);
        return Result.From(ok);
    }
}
